package com.d3works.apps.project.service;

import com.d3works.apps.project.db.ResourceBooking;
import com.d3works.apps.project.db.repo.ResourceBookingRepository;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.List;

public class ResourceBookingServiceImpl implements ResourceBookingService {

  @Inject ResourceBookingRepository resourceBookingRepo;

  @Override
  public boolean checkIfResourceBooked(ResourceBooking resourceBooking) {
    List<Object> params = new ArrayList<>();

    String query =
        "self.resource.id = ?1 AND self.fromDate != null AND self.toDate != null AND ((?2 BETWEEN self.fromDate AND self.toDate OR ?3 BETWEEN self.fromDate AND self.toDate) OR (self.fromDate BETWEEN ?2 AND ?3 OR self.toDate BETWEEN ?2 AND ?3))";
    params.add(resourceBooking.getResource().getId());
    params.add(resourceBooking.getFromDate());
    params.add(resourceBooking.getToDate());

    if (resourceBooking.getId() != null) {
      query += " AND self.id != ?4";
      params.add(resourceBooking.getId());
    }

    return resourceBookingRepo.all().filter(query, params.toArray()).count() > 0;
  }
}
